package com.ruijie.acl.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.jsf.ListDataModel;

import com.ruijie.acl.AccessGroup;
import com.ruijie.acl.TimeInfo;
import com.ruijie.acl.TimeRange;
import com.ruijie.acl.service.DeviceTimeRangeService;
import com.ruijie.acl.service.TimeInfoService;
import com.ruijie.acl.service.TimeRangeService;
import com.ruijie.acl.type.TimeInfoTypeEnum;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.foundation.bo.EntityObject;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.service.Repository;
import com.ruijie.foundation.utils.StringUtils;
import com.ruijie.foundation.web.intercept.AddSuccessInfo;

/**
 * <p>
 * Title: ACL时间列表管理Action类
 * 
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * 为ACL时间列表管理模块提供页面数据的显示、获取和页面的跳转。
 * 
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time:
 * </p>
 * <p>
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */

@Name("timeInfoAction")
@Scope(ScopeType.CONVERSATION)
@AddSuccessInfo
public class TimeInfoAction extends AclBaseAction {

	@In("#{timeInfoService}")
	private TimeInfoService timeInfoService;

	@In("#{timeRangeService}")
	private TimeRangeService timeRangeService;

	@In("#{deviceTimeRangeService}")
	private DeviceTimeRangeService deviceTimeRangeService;

	@In("#{timeRangeAction}")
	private TimeRangeAction timeRangeAction;

	/**
	 * 标识每周有效时间
	 */
	protected Map<String, Boolean> timeInfos = new HashMap<String, Boolean>();

	private TimeInfo model;

	private TimeInfo criteria = new TimeInfo();

	private ListDataModel timeListModel;

	public ListDataModel getEntityModelList(TimeRange timeRange) {
		// if(timeListModel == null) {
		this.setParentEntity(timeRange);
		List<TimeInfo> timerInfoList = this.timeInfoService.getByTimeRange(timeRange);
		timeListModel = new ListDataModel(timerInfoList);
		// }
		return timeListModel;
	}
	/**
	 * 
	 * @param timeRange
	 * @param flag 是否分页 false不分页;true分页
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public ListDataModel getEntityModelList(TimeRange timeRange,boolean flag) {
		// if(timeListModel == null) {
		this.setParentEntity(timeRange);
		if(flag){
			adjustPage();
			this.currentPage=this.timeInfoService.pageQueryByTimeInfo(timeRange, page, pageSize);
			this.timeListModel=new ListDataModel((List<TimeInfo>)this.currentPage.getResult());
		}else{
			List<TimeInfo> timerInfoList = this.timeInfoService.getByTimeRange(timeRange);
			timeListModel = new ListDataModel(timerInfoList);
		}		
		// }
		return timeListModel;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void updateModel() {
		timeInfos.clear();
		super.updateModel();
	}

	/**
	 * 更新时间段详细信息
	 */
	public void updateModel4TimeRangeAction() {
		if (this.getParentEntity() != null) {
			this.timeRangeAction.setModel((TimeRange) this.getParentEntity());
		}
	}

	@Override
	protected boolean doAdd() {
		TimeRange timeRange = (TimeRange) this.getParentEntity();
		this.model.setTimeRange(timeRange);
		String periodic = this.convertPeriodic();
		if (!AclUtil.empty(periodic)) {
			this.model.setPeriodic(periodic);
		}
		// 检测结束时间不能大于开始时间
		this.checkTime();
		// 检测是否已经存在时间信息
		if (this.timeInfoService.isExistTimeInfo(model, model.getId())) {
			throw new BusinessException("acl_validator_timeinfo_exited");
		}

		// 如果有变更，则处理。
		if (checkChanged()) {
			timeInfoService.update(this.model);
			if (this.isRelativeDevice(timeRange)) {
				// 更新"变更警示"
				timeRange = timeRangeService.get(timeRange.getId());
				timeRange.setIsChanged(true);
				timeRangeService.update(timeRange);
				deviceTimeRangeService.updateChangedByTimeRange(timeRange);
				this.setParentEntity(timeRange);
			}
		}

		// 清除多选框选定记录
		timeInfos.clear();
		updateModel4TimeRangeAction();
		return true;
	}

	@Override
	protected boolean doUpdate() {
		return this.doAdd();
	}

	/**
	 * 开始时间不能大于或者等于结束时间
	 */
	public void checkTime() {
		String startTimes[] = this.model.getStarttime().split(":");
		String endTimes[] = this.model.getEndtime().split(":");
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.set(2009, 10, 1, Integer.parseInt(startTimes[0]), Integer.parseInt(startTimes[1]), 0);
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.set(2009, 10, 1, Integer.parseInt(endTimes[0]), Integer.parseInt(endTimes[1]), 0);
		// 开始时间不能大于或者等于结束时间
		if (startCalendar.compareTo(endCalendar) >= 0) {
			throw new BusinessException("acl_link_used_error_single");
		}
	}

	/**
	 * 表示是否修改 如是Model不存在，或者不是更新，则返回TRUE
	 * 
	 * @return
	 */
	public boolean checkChanged() {
		if (this.model != null && this.model.getId() != null) {
			TimeInfo timeInfo = timeInfoService.get(this.model.getId());
			if (timeInfo.getStarttime().equals(model.getStarttime())
					&& timeInfo.getEndtime().equals(model.getEndtime())
					&& timeInfo.getPeriodic().equals(model.getPeriodic())) {
				return false;
			} else {
				timeInfo.setStarttime(this.model.getStarttime());
				timeInfo.setEndtime(this.model.getEndtime());
				timeInfo.setPeriodic(this.model.getPeriodic());
				timeInfo.setTimeRange(this.model.getTimeRange());
				this.model = timeInfo;
			}
		}
		return true;
	}

	/**
	 * 是否已经被设备关联。
	 * 
	 * @return 是否关联
	 */
	public boolean isRelativeDevice(TimeRange timeRange) {
		return deviceTimeRangeService.isExistDeviceTimeRange(null, timeRange);
	}

	/**
	 * 删除单个对象时的动作
	 * 
	 * @param entity
	 */
	@Override
	public void doSingleDelete(EntityObject entity) {
		TimeInfo timeInfo = (TimeInfo) entity;
		TimeRange timeRange = timeInfo.getTimeRange();
		if (this.isRelativeDevice(timeRange)) {
			timeRange = timeRangeService.get(timeRange.getId());
			// 更新"变更警示"
			timeRange.setIsChanged(true);
			timeRangeService.update(timeRange);
			deviceTimeRangeService.updateChangedByTimeRange(timeRange);
			this.setParentEntity(timeRange);
		}
		updateModel4TimeRangeAction();
	}
	
	 public void delete() {
	        if (null == getIds() || getIds().length == 0)
	            return;
	        try {
	        	Long[] ids = getIds();
	        	TimeRange timeRange = timeInfoService.get(ids[0]).getTimeRange();
	        	if (this.isRelativeDevice(timeRange)) {
	    			timeRange = timeRangeService.get(timeRange.getId());
	    			// 更新"变更警示"
	    			timeRange.setIsChanged(true);
	    			timeRangeService.update(timeRange);
	    			deviceTimeRangeService.updateChangedByTimeRange(timeRange);
	    			this.setParentEntity(timeRange);
	    		}
	    		updateModel4TimeRangeAction();
	            if (!doDelete()) {
	                return;
	            }
	        } catch (BusinessException e) {
	            // 清除多选框选定记录
	            selectedIds.clear();
	            throw e;
	        }

	        updateModel();
	        // 如果当前页面已经没有记录(例如删除了当前页面的所有记录)，那么显示上一页
	        if (currentPage.getTotalPageCount() < page && page > 1) {
	            page--;
	            updateModel();
	        }
	        
	        // 清除多选框选定记录
	        selectedIds.clear();
	        addGlobalI18nMessage(getDelSuccessMsg());
	        
	}

	/**
	 * 从列表页跳转到更新页面
	 * 
	 * @param model
	 * @return
	 */
	public String toTimeUpdate(EntityObject model) {
		TimeInfo timeInfo = (TimeInfo) model;
		timeInfos.clear();
		Map<String, Boolean> tempMap = new HashMap<String, Boolean>();
		if (!StringUtils.isNullOrEmpty(timeInfo.getPeriodic())) {
			String temps[] = timeInfo.getPeriodic().split(" ");
			for (String temp : temps) {
				if (!TimeInfoTypeEnum.daily.toString().equals(temp)
						&& !TimeInfoTypeEnum.weekdays.toString().equals(temp)
						&& !TimeInfoTypeEnum.weekend.toString().equals(temp)) {
					tempMap.put(temp, true);
				}
			}
		}
		setTimeInfos(tempMap);
		return super.toUpdatePage(model);
	}

	/**
	 * 获取每周有效时间的值
	 * 
	 * @return 有效时间字符串
	 */
	protected String convertPeriodic() {
		List<String> timeList = new ArrayList<String>();
		Set<String> ketSet = timeInfos.keySet();
		for (String key : ketSet) {
			if (timeInfos.get(key).equals(Boolean.TRUE)) {
				timeList.add(key);
			}
		}
		if (timeList.size() == 0) {
			return null;
		} else if (timeList.size() == 7) {
			// 星期一到星期日全部选择，有效时间改为每天
			return TimeInfoTypeEnum.daily.toString();
		} else {
			// 星期一到星期五，有效时间改为周一到周五
			if (timeList.size() == 5
					&& timeList.contains(TimeInfoTypeEnum.monday.toString())
					&& timeList.contains(TimeInfoTypeEnum.tuesday.toString())
					&& timeList.contains(TimeInfoTypeEnum.wednesday.toString())
					&& timeList.contains(TimeInfoTypeEnum.thursday.toString())
					&& timeList.contains(TimeInfoTypeEnum.friday.toString())) {
				return TimeInfoTypeEnum.weekdays.toString();
			}
			// 星期六到星期天，有效时间改为周末
			if (timeList.size() == 2 
					&& timeList.contains(TimeInfoTypeEnum.saturday.toString())
					&& timeList.contains(TimeInfoTypeEnum.sunday.toString())) {
				return TimeInfoTypeEnum.weekend.toString();
			}
			String resultString = "";
			for (String time : timeList) {
				resultString += " " + time;
			}
			if (resultString.length() > 0) {
				resultString = resultString.substring(1);
			}
			return resultString;
		}
	}

	public Map<String, Boolean> getTimeInfos() {
		return timeInfos;
	}

	public void setTimeInfos(Map<String, Boolean> timeInfos) {
		this.timeInfos = timeInfos;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Repository getRepository() {
		return this.timeInfoService;
	}

	@Override
	protected String getAddPage() {
		return "/acl/timeInfoAdd.seam";
	}

	@Override
	public EntityObject getCriteria() {
		return this.criteria;
	}

	@Override
	protected String getDetailPage() {
		return "/acl/timeRangeDetail.seam";
	}

	@Override
	protected String getListPage() {
		return "/acl/timeRangeDetail.seam";
	}

	@Override
	public EntityObject getModel() {
		return this.model;
	}

	@Override
	protected String getUpdatePage() {
		return "/acl/timeInfoEdit.seam";
	}

	@Override
	public void resetModel() {
		model = null;
		model = new TimeInfo();
	}

	protected Page pagedQuery(EntityObject criteria, int page, int pageSize) {
		return timeInfoService.pageQueryByTimeInfo((TimeRange) this.getParentEntity(), page, pageSize);
	}

	@Override
	public void setCriteria(EntityObject criteria) {
		this.criteria = (TimeInfo) criteria;
	}

	@Override
	public void setModel(EntityObject model) {
		this.model = (TimeInfo) model;
	}
	
	
	//-------------modify by sinyee 2010-10-22 being----------------

	public String toAddPageBlank(){
		this.toAddPage();
		return null;
	}
	
	@AddSuccessInfo
	public String addEntity(){
		this.add();
		return null;
	}

	public String toTimeUpdateBlank(EntityObject model){
		this.toTimeUpdate(model);
		return null;
	}
	
	@AddSuccessInfo
	public String updateEntity(){
		this.update();
		return null;
	}
	
	//--------------modify by sinyee 2010-10-22 end----------------
	
	
}
